1 Introduction

R is a programming language designed originally for performing statistical analyses. However, it’s potential has been increased and nowadays it can be used for general data analysis, creating atractive plots or even for creating websites! You can download R from the official repository: CRAN.

If you have used spreadsheets to calculate stuff, you have already programmed.

In R, you can assign values to variables using <-. You don’t have to type it everytime, just Alt+-!

variable <- 2342
variable
## [1] 2342

You can use R from the unix command line or download an Integrated Development Environment (IDE) such as RStudio.

2 Working with R in RStudio

  1. Code editor.
  2. R Console.
  3. Environment and History.
  4. Plots, help, files.

3 Programming

  • Functions.
  • If statements.
  • Loops.

4 R basics

4.1 Data types

The basic types of variables that can be represented in R are the following:

  • Numeric. 332, 0.234.
  • Character. "Barcelona", "woman". A special type of character is the class factor.
  • Logical. TRUE or FALSE.

You can check the type of variable using class().

Create one variable of each of the above-mentioned basic types and check that the type is correct using the class() function.
var <- "text" # character
class(var)
## [1] "character"
var <- 3242 # numeric
class(var)
## [1] "numeric"
var <- TRUE # logical
class(var)
## [1] "logical"

4.2 Arithmetic operators

Operator Description
+ addition
- subtraction
* multiplication
/ division
^ or ** exponentiation
3+4*5.2/2^2
## [1] 8.2

4.3 Logical operators

Operator Description
> greater than
>= greater than or equal to
== exactly equal to
!= not equal to
# Works with numerics
3 > 2
## [1] TRUE
# And also with characters
"class"=="class"
## [1] TRUE

4.4 Data structures

We can combine several data types into more complex structures. The different structures one can create in R are the following:

  • Vectors. Consists on a concatenation c() of values. The type of all values should be the same.
vector <- c(0,1,2,3,4,6)
vector
## [1] 0 1 2 3 4 6
  • Matrices. Are basically vectors, but with 2 dimensions (rows and columns). You can create a matrix using matrix(). You can check which arguments you can pass to the matrix function typing ?matrix or help(matrix)
mat <- matrix(vector, nrow=2)
mat
##      [,1] [,2] [,3]
## [1,]    0    2    4
## [2,]    1    3    6
As an example we just generated a vector of numbers. Try to generate a vector with letters (characters) from ‘a’ to ‘f’ and then convert it to a matrix with 2 columns.
vector <- c('a', 'b', 'c', 'd', 'e', 'f')
mat <- matrix(vector, ncol=2)
mat
##      [,1] [,2]
## [1,] "a"  "d" 
## [2,] "b"  "e" 
## [3,] "c"  "f"
  • Lists.
  • Dataframes.

5 Loading data

6 Functions and packages

7 Additional resources